<template>
  <view class="private-list-container">
    <!-- 私信列表 -->
    <scroll-view 
      class="chat-list" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      @refresherrefresh="onRefresh"
      :refresher-triggered="isRefreshing"
    >
      <!-- 加载状态 -->
      <view v-if="isLoading && privateChatList.length === 0" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 私信列表项 -->
      <view 
        v-for="chat in privateChatList" 
        :key="chat.id" 
        class="chat-item"
        @click="openPrivateChat(chat)"
      >
        <view class="avatar-container">
          <image
            v-if="chat.other_user?.avatar_url"
            :src="chat.other_user.avatar_url"
            class="user-avatar"
          />
          <view v-else class="avatar-placeholder">
            <text>{{ chat.other_user?.nickname?.charAt(0) || '用' }}</text>
          </view>
        </view>

        <view class="chat-content">
          <view class="chat-header">
            <text class="user-name">{{ chat.other_user?.nickname || '未知用户' }}</text>
            <text class="chat-time">{{ formatTime(chat.last_message_time) }}</text>
          </view>
          
          <view class="last-message">
            <text class="message-text">{{ chat.last_message || '暂无消息' }}</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="!isLoading && privateChatList.length === 0" class="empty-state">
        <text class="empty-icon">💬</text>
        <text class="empty-title">暂无私信</text>
        <text class="empty-desc">您还没有任何私信对话</text>
        <text class="empty-tip">点击群聊中的用户昵称可以发起私聊</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="isLoadingMore" class="loading-more">
        <text>加载更多...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMore && privateChatList.length > 0" class="no-more">
        <text>没有更多私信了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { chatAPI, utils } from '@/utils/api.js'

// 响应式数据
const privateChatList = ref([])
const isLoading = ref(false)
const isLoadingMore = ref(false)
const isRefreshing = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = ref({
  page: 1,
  pageSize: 20
})

// 生命周期
onLoad(() => {
  checkLoginAndLoad()
})

onShow(() => {
  // 每次显示页面时刷新数据
  refreshData()

  // 通知聊天页面清除未读私信数量
  uni.$emit('clearUnreadPrivateMessages')
})

// 方法定义
const checkLoginAndLoad = () => {
  const token = uni.getStorageSync('token')
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' })
    }, 1500)
    return
  }
  
  loadPrivateChatList()
}

const loadPrivateChatList = async (isRefresh = false) => {
  if (isLoading.value && !isRefresh) return
  
  try {
    if (isRefresh) {
      isRefreshing.value = true
      pagination.value.page = 1
    } else {
      isLoading.value = true
    }
    
    const response = await chatAPI.getPrivateChatList()
    
    if (response.success) {
      const newData = response.data || []
      console.log('私聊列表API返回数据:', newData) // 调试日志

      if (isRefresh) {
        privateChatList.value = newData
      } else {
        privateChatList.value = [...privateChatList.value, ...newData]
      }

      // 简单的分页逻辑，如果返回的数据少于pageSize，说明没有更多了
      hasMore.value = newData.length >= pagination.value.pageSize
    } else {
      uni.showToast({
        title: response.message || '获取私信列表失败',
        icon: 'none'
      })
    }
    
  } catch (error) {
    console.error('获取私信列表失败:', error)
    utils.handleError(error, '获取私信列表失败')
  } finally {
    isLoading.value = false
    isRefreshing.value = false
    isLoadingMore.value = false
  }
}

const loadMore = () => {
  if (!hasMore.value || isLoadingMore.value) return
  
  isLoadingMore.value = true
  pagination.value.page++
  loadPrivateChatList()
}

const onRefresh = () => {
  refreshData()
}

const refreshData = () => {
  privateChatList.value = []
  hasMore.value = true
  loadPrivateChatList(true)
}

const openPrivateChat = (chat) => {
  console.log('点击私聊项:', chat) // 调试日志

  if (!chat.other_user?.id) {
    uni.showToast({
      title: '用户信息错误',
      icon: 'none'
    })
    return
  }

  uni.navigateTo({
    url: `/pages/chat/private?userId=${chat.other_user.id}&nickname=${encodeURIComponent(chat.other_user.nickname || '用户')}`
  })
}

/**
 * 格式化时间 - 显示为**年**月*日 时:分:秒格式
 */
const formatTime = (timeStr) => {
  if (!timeStr) return ''

  const time = new Date(timeStr)
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const day = time.getDate()
  const hours = time.getHours().toString().padStart(2, '0')
  const minutes = time.getMinutes().toString().padStart(2, '0')
  const seconds = time.getSeconds().toString().padStart(2, '0')

  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

const goBack = () => {
  uni.navigateBack()
}
</script>

<style scoped>
.private-list-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.header {
  background: white;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.back-icon {
  font-size: 36rpx;
  color: #007aff;
}

.page-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.chat-list {
  flex: 1;
  padding: 0;
}

.loading-state {
  text-align: center;
  padding: 100rpx 20rpx;
}

.loading-text {
  color: #666;
  font-size: 28rpx;
}

.chat-item {
  background: white;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.chat-item:active {
  background: #f8f8f8;
}

.avatar-container {
  flex-shrink: 0;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
}

.avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #666;
  font-weight: bold;
}

.chat-content {
  flex: 1;
  min-width: 0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.user-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-time {
  font-size: 24rpx;
  color: #999;
  flex-shrink: 0;
  margin-left: 20rpx;
}

.last-message {
  display: flex;
  align-items: center;
}

.message-text {
  font-size: 28rpx;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 30rpx;
}

.empty-title {
  font-size: 32rpx;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.empty-desc {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.empty-tip {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.loading-more {
  text-align: center;
  padding: 30rpx;
  color: #666;
  font-size: 24rpx;
}

.no-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 24rpx;
}
</style>
